<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="申请人ID" prop="applicantId">
        <el-input
          v-model="queryParams.applicantId"
          placeholder="请输入申请人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实验室类型" prop="appliedLabType">
        <el-select v-model="queryParams.appliedLabType" placeholder="请选择实验室类型" clearable>
          <el-option
            v-for="dict in dict.type.lab_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学期" prop="appliedSemester">
        <el-input
          v-model="queryParams.appliedSemester"
          placeholder="请输入学期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="起始周" prop="startWeek">
        <el-input
          v-model="queryParams.startWeek"
          placeholder="请输入起始周"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束周" prop="endWeek">
        <el-input
          v-model="queryParams.endWeek"
          placeholder="请输入结束周"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="星期几" prop="appliedDay">
        <el-select v-model="queryParams.appliedDay" placeholder="请选择星期几" clearable>
          <el-option
            v-for="dict in dict.type.jwxt_day"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="节次" prop="appliedSession">
        <el-select v-model="queryParams.appliedSession" placeholder="请选择节次" clearable>
          <el-option
            v-for="dict in dict.type.jwxt_session"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生班级" prop="studentClass">
        <el-input
          v-model="queryParams.studentClass"
          placeholder="请输入学生班级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生人数" prop="studentCount">
        <el-input
          v-model="queryParams.studentCount"
          placeholder="请输入学生人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批员ID" prop="approverId">
        <el-input
          v-model="queryParams.approverId"
          placeholder="请输入审批员ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="applicationStatus">
        <el-select v-model="queryParams.applicationStatus" placeholder="请选择申请状态" clearable>
          <el-option
            v-for="dict in tea_Status"
            :key="dict"
            :label="dict"
            :value="dict"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['jwxt:tea_application:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jwxt:tea_application:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="single"
          @click="handleCheck"
          v-hasPermi="['jwxt:tea_application:check']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jwxt:tea_application:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['jwxt:tea_application:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tea_applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="applicationId" />
      <el-table-column label="申请人ID" align="center" prop="applicantId" />
      <el-table-column label="实验室类型" align="center" prop="appliedLabType">
        <template slot-scope="scope">
<!--          <dict-tag :options="dict.type.lab_type" :value="scope.row.appliedLabType"/>-->
          <el-button
            size="mini"
            type="success"
            v-if="scope.row.appliedLabType=='软件'"
          >{{ scope.row.appliedLabType }}</el-button>
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.appliedLabType=='网络'"
          >{{ scope.row.appliedLabType }}</el-button>
          <el-button
            size="mini"
            type="warning"
            v-if="scope.row.appliedLabType=='硬件'"
          >{{ scope.row.appliedLabType }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="学期" align="center" prop="appliedSemester" />
      <el-table-column label="起始周" align="center" prop="startWeek" />
      <el-table-column label="结束周" align="center" prop="endWeek" />
      <el-table-column label="星期几" align="center" prop="appliedDay">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jwxt_day" :value="scope.row.appliedDay"/>
        </template>
      </el-table-column>
      <el-table-column label="节次" align="center" prop="appliedSession">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jwxt_session" :value="scope.row.appliedSession"/>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="学生班级" align="center" prop="studentClass" />
      <el-table-column label="学生人数" align="center" prop="studentCount" />
      <el-table-column label="审批员ID" align="center" prop="approverId" />
      <el-table-column label="申请状态" align="center" prop="applicationStatus">
        <template slot-scope="scope">
<!--          <dict-tag :options="dict.type.jwxt_application_status" :value="scope.row.applicationStatus"/>-->
          <el-button
            size="mini"
            type="success"
            plain
            v-if="scope.row.applicationStatus=='已排课'"
          >{{ scope.row.applicationStatus }}</el-button>
          <el-button
            size="mini"
            type="info"
            plain
            v-if="scope.row.applicationStatus=='未排课'"
          >{{ scope.row.applicationStatus }}</el-button>
          <el-button
            size="mini"
            type="danger"
            plain
            v-if="scope.row.applicationStatus=='驳回'"
          >{{ scope.row.applicationStatus }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['jwxt:tea_application:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['jwxt:tea_application:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-line-round"
            @click="handleCheck(scope.row)"
            v-hasPermi="['jwxt:tea_application:check']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教师实验课申请登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="申请人ID" prop="applicantId">
          <el-input v-model="form.applicantId" placeholder="请输入申请人ID" />
        </el-form-item>
        <el-form-item label="实验室类型" prop="appliedLabType">
          <el-select v-model="form.appliedLabType" placeholder="请选择实验室类型">
            <el-option
              v-for="dict in dict.type.lab_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期"  prop="appliedSemester">
          <el-input v-model="form.appliedSemester" placeholder="请输入学期" disabled />
        </el-form-item>
        <el-form-item label="起始周">
          <el-slider
            v-model="weekRange"
            range
            :min="1"
            :max="20">
          </el-slider>
        </el-form-item>
        <el-form-item label="星期几" prop="appliedDay">
          <el-select v-model="form.appliedDay" placeholder="请选择星期几">
            <el-option
              v-for="dict in dict.type.jwxt_day"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节次" prop="appliedSession">
          <el-select v-model="form.appliedSession" placeholder="请选择节次">
            <el-option
              v-for="dict in dict.type.jwxt_session"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="学生班级" prop="studentClass">
          <el-input v-model="form.studentClass" placeholder="年份+专业+班级,例：2021软件工程4班" />
        </el-form-item>
        <el-form-item label="学生人数" prop="studentCount">
            <el-slider
              v-model="form.studentCount"
              show-input>
            </el-slider>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核教师实验课申请登记对话框 -->
    <el-dialog :title="title" :visible.sync="openCheck" width="500px" append-to-body>
      <el-form ref="formCheck" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请人ID" prop="applicantId">
          <el-input v-model="form.applicantId" placeholder="请输入申请人ID" disabled/>
        </el-form-item>
        <el-form-item label="实验室类型" prop="appliedLabType">
          <el-select v-model="form.appliedLabType" placeholder="请选择实验室类型"disabled>
            <el-option
              v-for="dict in dict.type.lab_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="appliedSemester">
          <el-input v-model="form.appliedSemester" placeholder="请输入学期" disabled/>
        </el-form-item>
        <el-form-item label="起始周" prop="startWeek">
          <el-input v-model="form.startWeek" placeholder="请输入起始周" disabled/>
        </el-form-item>
        <el-form-item label="结束周" prop="endWeek">
          <el-input v-model="form.endWeek" placeholder="请输入结束周" disabled/>
        </el-form-item>
        <el-form-item label="星期几" prop="appliedDay">
          <el-select v-model="form.appliedDay" placeholder="请选择星期几"disabled>
            <el-option
              v-for="dict in dict.type.jwxt_day"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节次" prop="appliedSession">
          <el-select v-model="form.appliedSession" placeholder="请选择节次" disabled>
            <el-option
              v-for="dict in dict.type.jwxt_session"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称"disabled />
        </el-form-item>
        <el-form-item label="学生班级" prop="studentClass">
          <el-input v-model="form.studentClass" placeholder="请输入学生班级" disabled/>
        </el-form-item>
        <el-form-item label="学生人数" prop="studentCount">
          <el-input v-model="form.studentCount" placeholder="请输入学生人数"disabled />
        </el-form-item>
        <el-form-item label="审核状态" prop="applicationStatus">
          <el-input v-model="form.applicationStatus" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePass">通过</el-button>
        <el-button type="primary" @click="handleReject">驳回</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核通过后填写 -->
    <el-dialog :title="title"  :visible.sync="afterCheck" width="500px" append-to-body>
      <el-form ref="labSelect" :model="labForm" :rules="labRules" label-width="100px">
        <el-form-item :label="'当前选择的实验室容量：' +curCount"  label-width="200px">
        </el-form-item>
        <el-form-item :label="'当前申请表目标容量：'+this.form.studentCount "  label-width="200px">
        </el-form-item>
        <el-form-item label="选择实验室" prop="labs">
          <el-select v-model="labForm.labs" placeholder="请选择选择实验室" clearable
                     :style="{width: '100%'}" multiple value-key="labId">
            <el-option
              v-for="dict in schedulerFormList"
              :key="dict.labId"
              :label="'实验室名字：  '+dict.labName+dict.labNumber+'   实验室容量：  '+dict.equipmentNumber"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelSelect">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listTea_application,
  getTea_application,
  delTea_application,
  addTea_application,
  updateTea_application,
  reject_application, get_validate_labs, pass_application
} from "@/api/jwxt/tea_application";
import CheckForm from "@/components/CheckForm";
const validateStudentCount= (rule,value,callback)=>{
  if(!value){
    return callback(new Error("学生人数不能为空！"));
  }else {
    if(value<=0){
      return callback(new Error("学生人数不能为0！"));
    }else {
      callback();
    }
  }
}
const validateLabs= (rule,value,callback)=>{
  if(!value){
    return callback(new Error(""));
  }else {
    if(value.length<=0){
      return callback(new Error(""));
    }else {
      callback();
    }
  }
}
export default {
  //#region data
  components:{
    CheckForm
  },
  name: "Tea_application",
  dicts: ['jwxt_day', 'jwxt_session', 'jwxt_application_status', 'lab_type'],
  data() {
    return {
      labForm:{
        labs:[]
      },
      tea_Status:['已排课','未排课','驳回','使用完毕'],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教师实验课申请登记表格数据
      tea_applicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单的周次的范围
      weekRange: [1,20],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicantId: null,
        appliedLabType: null,
        appliedSemester: null,
        startWeek: null,
        endWeek: null,
        appliedDay: null,
        appliedSession: null,
        courseName: null,
        studentClass: null,
        studentCount: null,
        approverId: null,
        applicationStatus: null
      },
      // 表单参数
      form: {
      },

      schedulerFormList:{},
      // 表单校验
      rules: {
        applicantId:[{ required: true, message: '该项为必填项', trigger: 'blur' }],
        appliedLabType: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        appliedSession: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        startWeek: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        endWeek: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        appliedDay: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        appliedSemester: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        courseName: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        studentClass: [{ required: true, message: '该项为必填项', trigger: 'blur' },
          { pattern:/\d{4}[^\d\s]+(?:\s+|\S)\d{1,2}班$/,message: "格式错误！例:2021软件工程4班",trigger: "blur"}],
        studentCount: [{ required: true, message: '学生人数不能为0',validator: validateStudentCount, trigger: 'blur' }],
      },
      labRules: {
        labs:[{ required: true,validator:validateLabs, message: '该项为必填项', trigger: 'blur' }],
      },
      // 是否显示弹出层
      openCheck: false,
      // 是否显示弹出层
      afterCheck: false
    };
  },
  created() {
    this.getList();
  },
  computed:{
    curCount(){
      if(this.afterCheck==false){
        this.labForm.labs=[];
      }
      let ans=0;
      for(let i in this.labForm.labs){
        let a=this.labForm.labs[i];
        ans+=a.equipmentNumber
      }
      return ans;
    },
    checkLabs(){
      return this.curCount>=this.form.studentCount;
    },
  },
  //#endregion
  methods: {

    //#region methods
    cancelSelect(){
      this.afterCheck=false;
    },
    /** 查询教师实验课申请登记列表 */
    getList() {
      this.loading = true;
      listTea_application(this.queryParams).then(response => {
        this.tea_applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openCheck = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applicationId: null,
        applicantId: null,
        appliedLabType: null,
        appliedSemester: null,
        startWeek: null,
        endWeek: null,
        appliedDay: null,
        appliedSession: null,
        courseName: null,
        studentClass: null,
        studentCount: 0,
        approverId: null,
        applicationStatus: null
      };
      this.resetForm("form");

    },
    /** 判断是否可以修改 */
    canUpdate(row) {
      return !row.approverId
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applicationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教师实验课申请登记";
      this.form.applicantId=this.$store.state.user.id;
      this.loading=true;
      this.getConfigKey("jwxt.curSemester").then(response => {
        this.form.appliedSemester = response.msg;
        this.loading=false;
      }).catch(e=>{
        this.loading=false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applicationId = row.applicationId || this.ids
      console.log(applicationId);
      getTea_application(applicationId).then(response => {
        this.form = response.data;
        console.log(this.form.applicationId);
        if(!this.canUpdate(this.form)){
          this.$modal.msgError("禁止操作已经通过审核的申请！")
          return;
        }
        this.open = true;
        this.title = "修改教师实验课申请登记";
      });
    },
    /** 审核按钮操作 */
    handleCheck(row) {
      this.reset();
      const applicationId = row.applicationId || this.ids
      getTea_application(applicationId).then(response => {
        this.form = response.data;
        this.openCheck = true;
        this.title = "审核教师申请登记";
      });
    },
    //#endregion
    //#region verify
    /** 通过按钮操作 */
    handlePass(row) {
      this.$refs.formCheck.validate(valid => {
        if (valid) {
          if (this.form.applicationId != null) {
            this.loading=true;
            this.title="选择实验室";
            get_validate_labs(this.form).then(r=>{
              this.schedulerFormList=r.data;
              this.openCheck=false;
              this.afterCheck=true;
              this.loading=false;
            })
          }
        }
      })
    },
    /** 驳回按钮操作 */
    handleReject(row) {
      console.log(row);
      this.$refs.formCheck.validate(valid => {
        if (valid) {

          if (this.form.applicationId != null) {
            this.form.approverId=this.$store.state.user.id;
            reject_application(this.form).then(r=>{
              this.$modal.msgSuccess("驳回成功");
              this.openCheck=false;
              this.afterCheck=false;
              this.getList();
            })
          }
        }
      });
    },
    handleConfirm(form){
      this.$refs.labSelect.validate(valid => {
        if (valid) {
          let a=[];
          if(this.checkLabs){
            this.loading=true;
            for(let i in this.labForm.labs) {
              this.form.approverId=this.$store.state.user.id;
              this.form.labId=this.labForm.labs[i].labId;
              a.push(pass_application(this.form));
            }
            Promise.all(a).then(()=>{
              this.afterCheck=false;
              this.loading=false;
              this.$modal.msgSuccess("审核通过");
              this.getList();
            }).catch(e=>{
              this.afterCheck=false;
              this.loading=false;
              this.$modal.msgSuccess('审核错误');
              this.getList();
            });
          }
          else {
            this.$modal.msgError("选择的实验室总容量过小");
          }
        }
        else {
          this.$modal.msgError("非法的表格");
        }
      });
    },
    //#endregion
    //#region submit
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.applicationId != null) {
            updateTea_application(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTea_application(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //#endregion submit
    //#region delete
    /** 删除按钮操作 */
    handleDelete(row) {
      const applicationIds=row.applicationId||this.ids;
      this.deleteAll(applicationIds);
    },
    deleteAll(rows){
      this.$modal.confirm('是否确认删除教师实验课申请登记编号为"' + rows + '"的数据项？').then(function() {
        return delTea_application(rows);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.$modal.msgError("删除失败");
      });
    },
    //#endregion
    /** 导出按钮操作 */
    handleExport() {
      this.download('jwxt/tea_application/export', {
        ...this.queryParams
      }, `tea_application_${new Date().getTime()}.xlsx`)
    }
  },
  watch:{
    weekRange(newValue){
      this.form.startWeek=newValue[0];
      this.form.endWeek=newValue[1];
    },
    form: {
      //深度监听对象内部属性的变化
      deep: true,
      handler(newVal) {
        this.weekRange = [newVal.startWeek, newVal.endWeek];
      }
    }
  }
};
</script>
